angular.module('furion.services.geolocation', [])

.factory 'Geolocation', ($rootScope)->
  obj = {
    device: ()->
      furion.utils.isDevice()

    getPosition: ()->
      geolocation = {}
      geolocation.get = false
      if !obj.device()
        geolocation.longitude = 120.1736405426505
        geolocation.latitude = 30.21748498672096
        geolocation.get = true
        obj.getCity(geolocation.longitude, geolocation.latitude)
        return geolocation
      
      onSuccess = (position)->
        console.log "定位信息position：#{position}"
        geolocation.latitude = position.coords.latitude
        geolocation.longitude = position.coords.longitude
        geolocation.get = true
        obj.getCity(geolocation.longitude, geolocation.latitude)

      onError = (error)->
        alert 'code' + error.code + '\n' + 'message' + error.message

      # watchID = navigator.geolocation.watchPosition(onSuccess, onError, {maximumAge: 3600000, timeout: 5000, enableHighAccuracy: true})
      watchID = navigator.geolocation.getCurrentPosition(onSuccess, onError, {maximumAge: 3600000, timeout: 5000, enableHighAccuracy: true})
      
      return geolocation

    getCity: (long, lat)->
      # map = new Map.Map()
      point = new BMap.Point(long, lat)
      # map.centerAndZoom(point,12)
      myFun = (result)->
        cityName = result.name
        window.localStorage.setItem('geolocation-cityname', cityName)
        # map.setCenter(cityName)
        # alert("当前定位城市:"+cityName)

      myCity = new BMap.LocalCity()
      myCity.get(myFun)
  }

  return obj
  
